// 2025/3/6
// https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
// 螺旋矩阵

class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            int m = matrix.size(), n = matrix[0].size(), k = 0;
            vector<int> pos = {0, 0};
            // 选择xy, 移动, 边界, 边界变化
            vector<vector<int>> moval = {{1, 1, n - 1, -1}, {0, 1, m - 1, -1}, {1, -1, 0, 1}, {0, -1, 0, 1}};
            vector<int> ans(m * n, 0);
            for(int i = 0; i < m * n; i++)
            {
                ans[i] = matrix[pos[0]][pos[1]];
                if(pos[moval[k][0]] == moval[k][2])
                {
                    int tmp = (k + 3) % 4;
                    moval[tmp][2] += moval[tmp][3];
                    k = (k + 1) % 4;
                }
                pos[moval[k][0]] += moval[k][1];
            }
            return ans;
        }
    };